﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.DBUtility;
using System.Data.OracleClient;
using Xiaov.SmartWeb.Application.Models;

namespace Xiaov.SmartWeb.Application.SZBBTree
{
  public partial class InitTableData : System.Web.UI.Page
  {
    private string tableName = "", dwbm = "", nf = "", yf = "";
    XMLVERSION modelXml = null;
    protected void Page_Load(object sender, EventArgs e)
    {
      if (Request.QueryString["tableName"] != null || Request.QueryString["dwbm"] != null ||
        Request.QueryString["nf"] != null || Request.QueryString["yf"] != null)
      {
        tableName = Request.QueryString["tableName"].ToString();
        dwbm = Request.QueryString["dwbm"].ToString();
        nf = Request.QueryString["nf"].ToString();
        yf = Request.QueryString["yf"].ToString();
        //将年份、月份、单位、发送给客户端
        HttpCookie cookies = new HttpCookie("UserSelectInfo");
        cookies.Values["DW"] = dwbm;
        cookies.Values["NF"] = nf;
        cookies.Values["YF"] = yf;
        cookies.Expires = DateTime.MaxValue;
        HttpContext.Current.Response.Cookies.Add(cookies);
        //InitVersion();
        modelXml = new XMLVERSION(nf, yf, dwbm, tableName);
        CreateReport();
        DataSet ds = GetDataXml();
        ds.WriteXml(Response.Output);
        //关键2：修改ContentType，告诉浏览器这不是Html而是XML(非必需，但这样方便浏览和调试)
        Response.ContentType = "text/xml";
        //关键3：告诉浏览器，这是数据，就不要缓存我了
        Response.CacheControl = "no-cache";
        //关键4：立即关闭Response，后继的html内容统统不要了
        Response.End();
      }
      else
      {
        Response.Write("");
      }

    }

    private DataSet GetDataXml()
    {
      StringBuilder strSql = new StringBuilder();
      strSql.Append("select ");
      strSql.Append(modelXml.SELECTFIELD);
      strSql.Append(" FROM  ");
      strSql.Append(tableName);
      strSql.Append(" where dwbm=:0 and nf=:1 and yf=:2 order by ");
      strSql.Append(modelXml.ORDERBY);

      OracleParameter[] parms = { new OracleParameter(":0", OracleType.VarChar, 10), new OracleParameter(":1", OracleType.VarChar, 20),
                                new OracleParameter("2",OracleType.VarChar,10)};
      parms[0].Value = dwbm;
      parms[1].Value = nf;
      parms[2].Value = yf;
      DataSet ds = DbHelperOra.Query(strSql.ToString(), parms);
      Dictionary<string, int> preDic = GetPre();
      List<string> zdList = GetZD();
      //string[] columnList = modelXml.SELECTFIELD.Split(new char[] { ',' });
      string zbbm = "", value = "", zd = "", key = "";

      //隐藏行
      for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
      {
        zbbm = ds.Tables[0].Rows[i]["zbbm"].ToString();
        if (modelXml.HIDDENROW.Contains(zbbm))
        {
          ds.Tables[0].Rows.RemoveAt(i);
          i--;
        }
      }
      foreach (DataRow dr in ds.Tables[0].Rows)
      {
        dr["ZBMC"] = GetZBMC(dr["ZBMC"].ToString(), dr["cj"].ToString());
        zbbm = dr["zbbm"].ToString();
        for (int i = 0; i < zdList.Count; i++)
        {
          zd = zdList[i];
          key = zbbm + "_" + zd;
          if (preDic.ContainsKey(key))
          {
            if (!string.IsNullOrEmpty(dr[zd].ToString()))
            {
              value = ViewPre(dr[zd].ToString(), preDic[key]);
              dr[zd] = value;
            }
          }
        }
      }
      return ds;
    }

    private string ViewPre(string value, int pre)
    {
      //value = "1.5678";
      //string basic = "1";
      //for (int i = 0; i < pre; i++)
      //{
      //  basic += "0";
      //}
      double preD = double.Parse(pre.ToString());
      double basicD = Math.Pow(10d, preD);
      double valueD = double.Parse(value);
      double dd = Math.Floor(valueD * basicD) / basicD;
      return dd.ToString();
    }
    private string GetZBMC(string zbmc, string cj)
    {
      if (string.IsNullOrEmpty(cj))
      {
        return zbmc;
      }
      int cjI = int.Parse(cj);
      for (int cjInd = 1; cjInd < cjI; cjInd++)
      {
        zbmc = "  " + zbmc;
      }
      return zbmc;
    }

    private void CreateReport()
    {
      if (!IsExist())
      {
        LoadProc("p_create");
      }
    }

    private bool IsExist()
    {
      return Maticsoft.DBUtility.DbHelperOra.Exists("select Count(1) from " + tableName
        + " where dwbm='" + dwbm + "' and nf='" + nf + "' and yf='" + yf + "'");
    }

    public bool LoadProc(string ProcdureName)
    {
      OracleParameter[] parameters ={
            new OracleParameter("v_bbbm",OracleType.VarChar,20),
　　     new OracleParameter("v_dwbm",OracleType.VarChar,20),
　　     new OracleParameter("v_nf",OracleType.Number,4),
            new OracleParameter("v_yf",OracleType.Number,2),
　　      };
      parameters[0].Value = tableName.ToUpper();
      parameters[1].Value = dwbm.ToUpper();
      parameters[2].Value = nf;
      parameters[3].Value = yf;
      try
      {
        OracleDataReader odr = Maticsoft.DBUtility.DbHelperOra.RunProcedure(ProcdureName, parameters); odr.Close();
        return true;
      }
      catch
      {
        return false;
      }
    }

    private Dictionary<string, int> GetPre()
    {
      Dictionary<string, int> preDic = new Dictionary<string, int>();
      string sql = "select * from ENCO_SJJDJJBL where bbbm=:0 ";
      OracleParameter[] parms = { new OracleParameter(":0", OracleType.VarChar, 10) };
      parms[0].Value = tableName;
      OracleDataReader dr = DbHelperOra.ExecuteReader(sql, parms);
      string key = "";
      while (dr.Read())
      {
        key = dr["zbbm"].ToString() + "_" + dr["zd"].ToString();
        preDic.Add(key, int.Parse(dr["sjjd"].ToString()));
      }
      dr.Close();
      return preDic;
    }

    private List<string> GetZD()
    {
      List<string> zdList = new List<string>();
      string sql = "select * from ENCO_bbzd where bbbm=:0 and zdsx>13 and sjlx='数字型'";
      OracleParameter[] parms = { new OracleParameter(":0", OracleType.VarChar, 10) };
      parms[0].Value = tableName;
      OracleDataReader dr = DbHelperOra.ExecuteReader(sql, parms);
      while (dr.Read())
      {
        zdList.Add(dr["zd"].ToString());
      }
      dr.Close();
      return zdList;
    }
  }
}